package org.activiti.engine.impl.cmd;

import org.activiti.engine.ActivitiException;
import org.activiti.engine.ActivitiIllegalArgumentException;
import org.activiti.engine.ActivitiObjectNotFoundException;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.runtime.ProcessInstance;

import java.io.Serializable;

public class SetProcessInstanceSecretLevelCmd implements Command<Void>, Serializable {
    private static final long serialVersionUID = 1L;

    protected String processInstanceId;
    protected Integer secretLevel;

    public SetProcessInstanceSecretLevelCmd(String processInstanceId, Integer secretLevel) {
        this.processInstanceId = processInstanceId;
        this.secretLevel = secretLevel;
    }

    @Override
    public Void execute(CommandContext commandContext) {
        if(processInstanceId == null) {
            throw new ActivitiIllegalArgumentException("processInstanceId is null");
        }

        ExecutionEntity execution = commandContext
                .getExecutionEntityManager()
                .findExecutionById(processInstanceId);

        if (execution==null) {
            throw new ActivitiObjectNotFoundException("process instance " + processInstanceId + " doesn't exist", ProcessInstance.class);
        }

        if(!execution.isProcessInstanceType()) {
            throw new ActivitiObjectNotFoundException("process instance " + processInstanceId +
                    " doesn't exist, the given ID references an execution, though", ProcessInstance.class);
        }

        if (execution.isSuspended()) {
            throw new ActivitiException("process instance " + processInstanceId + " is suspended, cannot set name");
        }

        // Actually set the name
        execution.setSecretLevel(this.secretLevel);

        // Record the change in history
        commandContext.getHistoryManager().recordProcessInstanceSecretLevelChange(processInstanceId, secretLevel);

        return null;
    }
}
